const got = require('got')

const ksHttpHeaders2222222 = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
}

const ksHttpHeaders = {
    accept: '*/*',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
    accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    connection: 'keep-alive',
    Host: 'live.kuaishou.com',
    'sec-ch-ua': `Google Chrome;v=107, Chromium;v=107, Not=A?Brand;v=24`,
    // Referer: 'https://live.kuaishou.com',
    'sec-ch-ua-platform': 'macOS',
    'Sec-Fetch-Dest': 'document',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'same-origin',
    'Sec-Fetch-User': '?1'
}

const getKuaiShouRoomInfo = (liveUrl) => {
    return new Promise(async (resolve, reject) => {
        const liveInfo = {
			wssAddress: '',
			token: '',
			liveStreamId: '',
			cookie: '',
			cookieObj: {},
		}
		const res = await got.get(liveUrl, {
			headers: ksHttpHeaders
		})
		const setCookies = res.headers['set-cookie']
        //从setCookies中 提取 cookie
        setCookies.forEach((c, i) => {
            liveInfo.cookie += `${i === 0 ? '' : ';'} ${c.split(';')[0]}`
            const objSplit = c.split(';')[0].split('=')
            liveInfo.cookieObj[objSplit[0]] = objSplit[1]
        })
		//从html中 提取 的正则表达式对象
		const regs = {
			stream: new RegExp(/screenshot\/(.*?)\~/, 'g'),
			stream2: new RegExp(/\"liveStream\"(.*?)\"poster\"\:/, 'g'),
			token: new RegExp(/token\"\:\"(.*?)\"\}\,\"status/, 'g'),
			wss: new RegExp(/wss:(.*?)\"\]/, 'g'),
			wsinfo: new RegExp(/\"websocketInfo(.*?)\"status\"/, 'g')
		}
		//从html中 提取 liveStreamId
		try {
			let match2 = res.body.match(regs.stream2);
			if(match2.length > 0){ //方式1
				let s1 = match2[0].match(new RegExp(/id\"\:\"(.*?)\"\,/, 'g'));
				if(s1.length){
					liveInfo.liveStreamId = s1[0].replace(/\"\,/g, '').replace(/id\"\:\"/g, '');
				}
			}
			if(!liveInfo.liveStreamId){ //方式2
				liveInfo.liveStreamId = res.body.match(regs.stream)[0].replace(/\~/g, '').split('/')[1]
			}
			if(!liveInfo.liveStreamId) return reject(`获取liveStreamId错误E1`);
		} catch (e) {
            return reject(`获取liveStreamId错误E2`);
		}
		//从html中 提取 websocket 信息
		try {
			let strA = res.body.match(regs.wsinfo)[0].replace(/\"websocketInfo\"\:/g, '');
			strA = strA.replace(/\,\"status\"/g, '');
			const jsonObj = JSON.parse(strA);
			liveInfo.wssAddress = jsonObj?.webSocketAddresses[0] || '';
			liveInfo.token = jsonObj.token || '';
			if(!liveInfo.wssAddress || !liveInfo.token) return reject(`获取Wss地址和Token错误E1`);
		} catch (e) {
            return reject(`获取Wss地址和Token错误E2`);
		}
		/*
		//从html中 提取 token
		console.log(res.body.match(regs.token));
		try {
			liveInfo.token = res.body.match(regs.token)[0].replace(/\"\]/g, '');
			liveInfo.token = eval('"' + liveInfo.token + '"');
		} catch (e) {
            return reject(`获取Token错误`);
		}
		//从html中 提取 wss
		try {
			liveInfo.wssAddress = res.body.match(regs.wss)[0].replace(/\"\]/g, '');
			liveInfo.wssAddress = eval('"' + liveInfo.wssAddress + '"');
		} catch (e) {
            return reject(`获取wssAddress错误`);
		}
		*/
		resolve(liveInfo);
    });
}

module.exports = {
    ksHttpHeaders,
    getKuaiShouRoomInfo
}